package middleware

import (
	"duoke/service"
	"duoke/tables"
	"duoke/utils/gjwt"
	"duoke/utils/orm"
	"duoke/utils/response"
	"github.com/gin-gonic/gin"
)

func AccountAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 登录验证
		utoken := c.Request.Header.Get("D-Token-S")
		if utoken == "" {
			utoken = c.DefaultQuery("token", "")
		}
		if utoken == "" {
			response.Response(c, 50008, "无权限访问", nil)
			c.Abort()
			return
		}
		result, err := gjwt.Parse(utoken)
		if err != nil {
			response.Response(c, 50014, err.Error(), nil)
			c.Abort()
			return
		}

		if result.Uid == 0 {
			response.Response(c, 50014, "请重新登录", nil)
			c.Abort()
			return
		}

		// 初始化全局账户信息
		c.Set("uid", result.Uid)
		if result.Role == "goods" {
			newAccount := new(tables.Account)
			has, _ := orm.Db.ID(result.Uid).Get(newAccount)
			if has {
				if newAccount.BindGoodsIds == "" {
					newAccount.BindGoodsIds = "-1"
				}
				c.Set("account", service.AccountStruct{Id: result.Uid, Role: result.Role, GoodsIds: newAccount.BindGoodsIds, Pid: result.Pid})
			} else {
				if result.GoodsIds == "" {
					result.GoodsIds = "-1"
				}
				c.Set("account", service.AccountStruct{Id: result.Uid, Role: result.Role, GoodsIds: result.GoodsIds, Pid: result.Pid})
			}
		} else {
			c.Set("account", service.AccountStruct{Id: result.Uid, Role: result.Role, GoodsIds: result.GoodsIds, Pid: result.Pid})
		}
		c.Next()
	}
}
